<?php
/**
* @file users.php
* Copyright (c) Friends Group. All rights reserved.
* $Id$
*
*/

require_once(realpath(dirname(__FILE__)) . '/../config.php');
require_once(realpath(dirname(__FILE__)) . '/../includes/common/ServiceFactory.php');

Session::start();

$commonService = ServiceFactory::get();
$userService = ServiceFactory::get("UserService");
$authService = ServiceFactory::get("AuthenticationService");

if(!$authService -> isAuthenticated())
    Response::redirect(Response::addQueryArg(array("back" => $_SERVER['REQUEST_URI']), "./login.php"));

$user = $authService -> getCurrentUser();

if($authService -> isUser($user))
    die("Access denied!");

$currentFile = 'users.php';
$action = $_REQUEST['action'];
$referer = $_REQUEST['referer'];
$userIds = $_REQUEST['users'];

if ( empty($action) ) {
    if ( isset($_REQUEST['deleteit']) )
        $action = 'delete';
    elseif ( isset($_REQUEST['changeit']) )
        $action = 'promote';
}

if(!empty($action) && empty($userIds))
    Response::redirect($referer);

switch ($action) 
{

    case 'promote':
        
        if( $authService -> isSuperAdministrator($user))
        {
            if(empty($userIds))
                Response::redirect($referer);
            
            if(!empty($_REQUEST['newRole']))
            {
                foreach ( (array) $userIds as $id) 
                {
                    if($id == $user -> getID())
                    {
                        RedirectMessage::info("Bạn không thể thay đổi quyền của chính mình!", "Error");
                        Response::redirect($referer);
                    }
                }
                
                try 
                {
                    $changeCount = 0;
                    foreach ((array)$userIds as $id) 
                    {
                        $userService -> setUserRole($id, $commonService -> getRoleByName($_REQUEST['newRole']));
                        $changeCount ++;
                    }
                    if($changeCount > 0)
                        RedirectMessage::info("Cập nhật Quyền của User thành công.");
                } 
                catch (Exception $ex) 
                {
                    RedirectMessage::info($ex -> getMessage(), "Error");
                }
            }
        }
        else
            RedirectMessage::info("Bạn không có quyền thay đổi Quyền của (các) User này.", "Error");
        
        Response::redirect($referer);
        
    break;
    
    case 'delete':
        if(empty($userIds))
            Response::redirect($referer);
        
        foreach ( (array) $userIds as $id) 
        {
            if($id == $user -> getID())
            {
                RedirectMessage::info("Bạn không thể xóa chính mình!", "Error");
                Response::redirect($referer);
            }
        }
        
        include("admin-header.php");
        include("menu-bar.php");
?>
<form id="postsFilter" action="" method="get">
    <h2>Quản lý tài khoản</h2>
    <div class="InfoArea">
        <div class="InfoItem Warning">
            <h4>Bạn có chắc là muốn xóa các Tài khoản này?</h4>
                <ul>
                <?php
                    foreach ( (array) $userIds as $id) 
                    {
                        $name = $userService -> findUserById($id) -> getNickname();
                        echo "<input type=\"hidden\" name=\"users[]\" value=\"$id\" />";
                        echo "<li><a href='profile.php?user=$name'>$name</a></li>";
                    }
                ?>
                </ul>
        </div> 
    </div>
    <div class="Command">
        <input type="hidden" name="action" value="dodelete" />
        <input type="hidden" value="<?php echo ($referer); ?>" name="referer" />
        <input type="submit" class="Button" value="Tôi chắc chắn" />
        <input type="button" class="Button" name="canceldelete" value="Không, tôi ấn nhầm nút" onclick="window.location='<?php echo $referer ?>'" />
    </div>
</form>
<?php
    include("admin-footer.php");
    exit();

    case 'dodelete':
        
        try 
        {
            if(empty($userIds))
                Response::redirect($referer);
            
            $deleteCount = 0;
            foreach ( (array) $userIds as $id) 
            {
                $userService -> deleteUser($id);
                ++$deleteCount;
            }
            RedirectMessage::info("$deleteCount User đã được xóa thành công.");
        }
        catch (Exception $ex) 
        {
            RedirectMessage::info($ex -> getMessage(), "Error");
        }
        
        Response::redirect($referer);
        
    break;
    
    default:
        include("admin-header.php");
        include("menu-bar.php");
}

if(RedirectMessage::hasMessage())
{
    InfoArea::showInfo(RedirectMessage::getMessage(), RedirectMessage::getMessage('title'), RedirectMessage::getMessage('type'));
    RedirectMessage::removeMessage();
}

?>

<form id="postsFilter" action="" method="get">
    <h2>Quản lý tài khoản</h2>
    <?php 
    $countUser = (count($commonService -> getUsersByRole(null)));
    if(!$authService -> isSuperAdministrator($user))
        $countUser = (count($commonService -> getUsersByRole($commonService -> getRoleByName("User"))));
    
    if($countUser) 
    {
    ?>
        
    <ul class="SubSubSub">
        <?php 
            $roleParam = null;
            if(isset($_REQUEST['role']))
                $roleParam = $_REQUEST['role'];
        ?>
        <li><a href="users.php" <?php if($roleParam == null) echo 'class="Current" '; ?>>Tất cả tài khoản</a></li>
        <?php 
            if($authService -> isSuperAdministrator($user))
            {                
                $roles = $commonService -> getAllRoles(); 
                foreach ($roles as $role)
                {
                    $cuir = $commonService -> countUserByRole($role);
                    $cr = ($roleParam==$role -> getRoleName())?"Current":"";
                    
                    if($cuir > 0)
                        echo "<li> | <a href='users.php?role={$role -> getRoleName()}' class='$cr'>{$role -> getRoleName()} ($cuir)</a></li>";
                }
            }
            else
                $roleParam = "User";
        ?>
    </ul>
    <input type="hidden" value="<?php echo ($_SERVER['REQUEST_URI']); ?>" name="referer" />
    <div class="TableNav">
        <div>
            <input value="Delete" name="deleteit" class="Button" type="submit" />
            <?php 
            if($authService -> isSuperAdministrator($user)) 
            {
            ?>
            <select name="newRole">
                <option value="">Thay đổi quyền…</option>
                <?php 
                foreach ($roles as $role)
                {
                    echo "<option value=\"{$role -> getRoleName()}\">{$role -> getRoleName()}</option>";
                }
                ?>
            </select>
            <input value="Change" name="changeit" class="Button" type="submit" />
            <?php } ?>
        </div>
        <br class="Clear">
    </div>
    <br class="Clear">
    <table class="TableWrapper" width="100%">
        <colgroup>
            <col width="2%">
            <col width="1%">
            <col width="20%">
            <col width="20%">
            <col width="20%">
            <col width="12%">
            <col width="12%">
            <col width="10">
        </colgroup>
        <thead>
            <tr>
                <th><input onclick="checkAll(this, document.getElementById('postsFilter'));" type="checkbox"> </th>
                <th>Avatar</th>
                <th>Username</th>
                <th>Name</th>
                <th>E-mail</th>
                <th>Quyền</th>
                <th>Ngày đăng ký</th>
                <th>Status</th>
            </tr>
        </thead>
        <tbody id="users" class="UserList">
            <?php 
            $class = "";
            $users = $commonService -> getUsersByRole($commonService -> getRoleByName($roleParam));
            if(count($users))
            foreach ($users as $user)
            {
                $class = $class == ""?"Alternate":"";
                $userId = $user -> getID();
                echo "<tr id='user-$userId' class='$class Username {$userService -> getUserRole($userId) -> getRoleName()}'>";
                echo "<td><input name='users[]' id='user_$userId' value='$userId' type='checkbox'></th>";
                echo "<td><img title=\"{$user -> getNickname()}'s avatar\" alt=\"{$user -> getNickname()}'s avatar\" class='Avatar' src='{$commonService -> getAvatarSrc($user -> getAvatarID(), 2)}' /></td>";
                echo "<td><strong><a href=profile.php?user={$user -> getNickname()}>{$user -> getNickname()}</a></strong></td>";
                echo "<td>{$user -> getFirstname()}&nbsp;{$user -> getLastname()}</td>";
                echo "<td><a href='mailto:{$user -> getEmail()}' title='e-mail: {$user -> getEmail()}'>{$user -> getEmail()}</a></td>";
                echo "<td>{$userService -> getUserRole($userId) -> getRoleName()}</td>";
                $rt = DateUtility::friendlyDate($user -> getRegistered());
                echo "<td>{$rt}</td>";
                echo "<td>" . $userService -> getUserStatus($user -> getID()) -> getStatusText() . "</td>";
                echo "</tr>";
            }
            ?>
        </tbody>
    </table>
    <?php } ?>
</form>
<?php include("admin-footer.php") ?>
